package com.example.apollotogit.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.apollotogit.config.RedisClient;
import com.example.apollotogit.service.HandleService;
import com.example.apollotogit.service.imp.HandleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dejax/handle")
public class HandleController {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private HandleService handleService;

    @Autowired
    RedisClient redisClient;

    @Value("${redis.key}")
    private String myKey;

    /*@Scheduled(fixedRate = 86400000)
    @RequestMapping("/start")
    public void schedule() throws InterruptedException {
        while (true) {
            Long size = redisClient.getSize(myKey);
            //监听到key值变化，判断key是否含有值
            if (size > 0) {
                System.out.println("redis size = " + size + "-----" + dateFormat.format(new Date()));
                for (Long i = size; i > 0; i--) {
                    String s = (String) redisClient.brpop(myKey, 0, TimeUnit.SECONDS);
                    Map map1 = (Map) JSON.parse(s);
                    //判断参数是否为空
                    if (!map1.isEmpty()) {
                        System.out.println("start solve");
                        //调用逻辑进行自动拉取
                        try {
                            handleService.getPrintInfo(map1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } else {
                Thread.sleep(20000);
            }
            System.gc();
        }
    }*/

    /**
     * 接收传递的集合参数
     *
     * @param jsonStrMap json集合参数
     */
    //@RequestMapping("getMergeResult")
    public String getMergeResult(@RequestBody JSONObject jsonStrMap) throws Exception {
        //存入redis
        String s = JSONObject.toJSONString(jsonStrMap);
        boolean lpush = redisClient.lpush(myKey, s);
        String result = "";
        if (lpush) {
            result = "success";
        } else {
            result = "error";
        }
        return result;
    }

}
